package com.mhy.crash;


import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created By Mahongyin
 * Date    2025/2/10 13:04
 */
public class HYCrashLifecycle implements Application.ActivityLifecycleCallbacks {
    private volatile static HYCrashLifecycle instance;
    private Activity currentActivity;

    public static HYCrashLifecycle getInstance() {
        if (instance == null) {
            synchronized (HYCrashLifecycle.class) {
                if (instance == null) {
                    instance = new HYCrashLifecycle();
                }
            }
        }
        return instance;
    }


    public void init(Application application) {
        application.registerActivityLifecycleCallbacks(this);
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
        // 更新 currentActivity 变量为当前启动的 Activity 实例
        this.currentActivity = activity;
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        // 如果销毁的 Activity 是当前的 Activity 实例，则将 currentActivity 置为 null
        if (activity == currentActivity) {
            currentActivity = null;
        }
    }

    @Nullable
    public Activity getCurrentActivity() {
        return currentActivity;
    }

    public void finishCurrentActivity() {
        if (currentActivity != null) {
            currentActivity.finish();
        }
    }

    public void finishAllActivity() {
        if (currentActivity != null) {
            currentActivity.finishAndRemoveTask();
        }
    }

    public void unInit(Application application) {
        application.unregisterActivityLifecycleCallbacks(this);
    }

}
